package com.cyan.note.controller;

import com.cyan.note.dto.auth.LoginRequest;
import com.cyan.note.entity.User;
import com.cyan.note.mapper.UserMapper;
import com.cyan.note.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 简化版认证控制器 - 用于测试登录功能
 * 
 * @author ZhangzhenYu
 * @since 2025-01-14
 */
@Slf4j
@RestController
@RequestMapping("/test/auth")
@RequiredArgsConstructor
public class SimpleAuthController {
    
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;
    
    /**
     * 简化版登录测试
     */
    @PostMapping("/login")
    public Map<String, Object> login(@Valid @RequestBody LoginRequest loginRequest) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("开始登录测试，用户名: {}", loginRequest.getUsername());
            
            // 1. 查找用户
            log.info("步骤1: 开始查找用户");
            User user = userMapper.findByUsername(loginRequest.getUsername());
            if (user == null) {
                log.info("步骤1: 用户不存在");
                result.put("success", false);
                result.put("message", "用户不存在");
                return result;
            }
            
            log.info("步骤1完成: 找到用户: {}, 角色: {}", user.getUsername(), user.getRole());
            log.info("用户详细信息: id={}, realName={}, status={}, shopId={}", 
                user.getId(), user.getRealName(), user.getStatus(), user.getShopId());
            
            // 2. 验证密码
            log.info("步骤2: 开始验证密码");
            log.info("输入密码: {}, 数据库密码hash: {}", 
                loginRequest.getPassword(), user.getPassword());
            
            if (user.getPassword() == null) {
                log.error("步骤2失败: 数据库中用户密码为null");
                result.put("success", false);
                result.put("message", "用户密码数据异常");
                return result;
            }
            
            boolean passwordMatches = passwordEncoder.matches(loginRequest.getPassword(), user.getPassword());
            log.info("步骤2完成: 密码验证结果: {}", passwordMatches);
            
            if (!passwordMatches) {
                result.put("success", false);
                result.put("message", "密码错误");
                return result;
            }
            
            // 3. 生成Token
            log.info("步骤3: 开始生成Token");
            log.info("Token参数: userId={}, username={}, role={}, shopId={}", 
                user.getId(), user.getUsername(), user.getRole(), user.getShopId());
            
            String token = jwtUtil.generateToken(
                user.getId(),
                user.getUsername(),
                user.getRole(),
                user.getShopId()
            );
            
            log.info("步骤3完成: Token生成成功，长度: {}", token != null ? token.length() : "null");
            
            // 4. 返回结果（简化版，不查询Shop信息）
            log.info("步骤4: 开始构建返回结果");
            
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("realName", user.getRealName());
            userInfo.put("role", user.getRole());
            userInfo.put("shopId", user.getShopId());
            userInfo.put("status", user.getStatus());
            
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("tokenType", "Bearer");
            data.put("userInfo", userInfo);
            
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("data", data);
            
            log.info("步骤4完成: 用户 {} 登录成功", user.getUsername());
            return result;
            
        } catch (Exception e) {
            log.error("登录过程中发生异常", e);
            result.put("success", false);
            result.put("message", "登录失败: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
            result.put("stackTrace", java.util.Arrays.toString(e.getStackTrace()).substring(0, Math.min(500, java.util.Arrays.toString(e.getStackTrace()).length())));
            return result;
        }
    }
    
    /**
     * 测试密码编码
     */
    @GetMapping("/test-password")
    public Map<String, Object> testPassword() {
        Map<String, Object> result = new HashMap<>();
        
        // 测试密码: admin123
        String rawPassword = "admin123";
        String encodedFromDb = "$2a$10$N9qo8uLOickgx2ZMRZoMye1JlOrY4d7LUY2LzxZOZd8W3d9v4/pGW";
        
        boolean matches = passwordEncoder.matches(rawPassword, encodedFromDb);
        
        // 生成新的正确密码hash
        String newHash = passwordEncoder.encode(rawPassword);
        boolean newMatches = passwordEncoder.matches(rawPassword, newHash);
        
        result.put("rawPassword", rawPassword);
        result.put("oldEncodedPassword", encodedFromDb);
        result.put("oldMatches", matches);
        result.put("newEncodedPassword", newHash);
        result.put("newMatches", newMatches);
        result.put("encoderClass", passwordEncoder.getClass().getSimpleName());
        
        return result;
    }
    
    /**
     * 生成密码hash
     */
    @GetMapping("/generate-password/{password}")
    public Map<String, Object> generatePassword(@PathVariable String password) {
        Map<String, Object> result = new HashMap<>();
        
        String encoded = passwordEncoder.encode(password);
        boolean matches = passwordEncoder.matches(password, encoded);
        
        result.put("rawPassword", password);
        result.put("encodedPassword", encoded);
        result.put("matches", matches);
        
        return result;
    }
    
    /**
     * 临时接口：修复数据库中的密码hash
     */
    @PostMapping("/fix-admin-password")
    public Map<String, Object> fixAdminPassword() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 生成正确的admin123密码hash
            String correctHash = passwordEncoder.encode("admin123");
            
            // 这里应该调用UserMapper的更新方法，但我们暂时先返回SQL
            result.put("success", true);
            result.put("message", "请在数据库中执行以下SQL");
            result.put("sql", "UPDATE users SET password = '" + correctHash + "' WHERE username = 'admin';");
            result.put("newPasswordHash", correctHash);
            
            // 验证新hash是否正确
            boolean matches = passwordEncoder.matches("admin123", correctHash);
            result.put("verified", matches);
            
            return result;
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "生成密码失败: " + e.getMessage());
            return result;
        }
    }
}